package com.online.shopping.service.impl;

import com.alibaba.fastjson.JSON;
import com.online.shopping.mapper.TbSpecificationOptionMapper;
import com.online.shopping.mapper.TbTypeTemplateMapper;
import com.online.shopping.pojo.TbSpecificationOption;
import com.online.shopping.pojo.TbSpecificationOptionExample;
import com.online.shopping.pojo.TbTypeTemplate;
import com.online.shopping.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author Rui
 * @version 1.0
 * @date 2020/11/15 13:13
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private TbTypeTemplateMapper templateMapper;

    @Autowired
    private TbSpecificationOptionMapper specificationOptionMapper;

    public List<TbTypeTemplate> findAllTemps(){
        return templateMapper.selectByExample(null);
    };

    public TbTypeTemplate findTempById(Long id){
        return templateMapper.selectByPrimaryKey(id);
    };

    public int addTemp(TbTypeTemplate template){
        return templateMapper.insert(template);
    };

    public void delTemp(Long id){
        templateMapper.deleteByPrimaryKey(id);
    };

    public int updateTemp(TbTypeTemplate template){
        return templateMapper.updateByPrimaryKeySelective(template);
    };

    @Override
    public List<Map> findSpecList(Long id) {
        //根据ID查询到模板对象
        TbTypeTemplate typeTemplate = templateMapper.selectByPrimaryKey(id);
        // 获得规格的数据spec_ids
        String specIds = typeTemplate.getSpecIds();// [{"id":27,"text":"网络"},{"id":32,"text":"机身内存"}]
        // 将specIds的字符串转成JSON的List<Map>
        List<Map> list = JSON.parseArray(specIds, Map.class);
        // 获得每条记录:
        for (Map map : list) {
            // 根据规格的ID 查询规格选项的数据:
            // 设置查询条件:
            TbSpecificationOptionExample example = new TbSpecificationOptionExample();
            TbSpecificationOptionExample.Criteria criteria = example.createCriteria();
            criteria.andSpecIdEqualTo(Long.valueOf((Integer) map.get("id")));

            List<TbSpecificationOption> specOptionList = specificationOptionMapper.selectByExample(example);
            //查询tb_specification_oprion表，加载option_name字段，然后封装到map中
            map.put("options", specOptionList);//{"id":27,"text":"网络",options:[{id：xxx,optionName:移动2G}]}
            System.out.println(map);
        }
        return list;
    }
}
